// register center in host

var http = require('http');
var url = require('url');
var querystring = require('querystring');
var path = require('path');
var fs = require('fs');

var __port = 8080;
var __cluster_node_number = 3;
var cluster_ip = {};

var server = http.createServer(function(req, res) {

	//
	var reqUrl = url.parse(req.url);
	var qs = querystring.parse(reqUrl.query);

	// client re__port their ip
	cluster_ip[qs.order] = qs.ip;

	var ret = {};
	if (Object.keys(cluster_ip).length < __cluster_node_number) {
		ret.ready = false;
		response(res, ret, qs);
	} else {
		ret.ready = true;
		ret.info = cluster_ip;

		changeLocalTestFile(cluster_ip[1], cluster_ip[2], cluster_ip[3], function() {
			response(res, ret, qs);
		});
	}
});

function response(res, ret, qs) {
	console.log('request:', qs, '======>', ret);
	// 
	res.writeHead(200, {
		'Content-type': 'application/json'
	});
	res.end(JSON.stringify(ret));
}

function __getIp() {
	var ifaces = require('os').networkInterfaces();
	var ips = {};
	for (var dev in ifaces) {
		ifaces[dev].forEach(function(details) {
			if (details.family === 'IPv4') {
				ips[dev] = details.address;
			}
		});
	}
	return ips.eth0 || ips.wlan0;
}
var localIp = __getIp();

server.listen(__port, function() {
	console.log('server start @ ' + localIp + ':' + __port);
});

// update some files
(function update() {
	var __file = path.join(__dirname, 'all_test.txt');
	console.log('update ' + __file);
	fs.readFile(__file, 'utf8', function(err, res) {
		if (err) {
			console.log('read ' + __file + ' fail');
			cb();
		} else {
			var str = res.replace(/\$serverHost/g, localIp);
			str = str.replace(/\$port/g, __port);
			// console.log(str);

			// write back
			fs.writeFile(__file, str, function(err) {
				if (err) {
					console.log('write ' + __file + ' fail');
				}
			});
		}
	});
})();


var once = 0;

function changeLocalTestFile(h1, h2, h3, cb) {
	// read and over write
	if (once > 0) {
		return cb();
	}

	once++;
	var __file = path.join(__dirname, 'all_test.txt');
	console.log('update ' + __file);
	fs.readFile(__file, 'utf8', function(err, res) {
		if (err) {
			console.log('read ' + __file + ' fail');
			cb();
		} else {
			var str = res.replace(/\$host1/g, h1);
			str = str.replace(/\$host2/g, h2);
			str = str.replace(/\$host3/g, h3);
			console.log(str);

			// write back
			fs.writeFile(__file, str, function(err) {
				if (err) {
					console.log('write ' + __file + ' fail');
				}
				cb();
			});
		}
	});
}